using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using ig.app.Services.ig.app.Services;
using Xamarin.Forms;

[assembly: Dependency(typeof(ig.app.Droid.DependencyServices.IPAddressManager))]

namespace ig.app.Droid.DependencyServices
{
    class IPAddressManager : IIPAddressManager
    {
        public async Task<string[]> GetIPAddress()
        {
            IPAddress[] adresses = await Dns.GetHostAddressesAsync(Dns.GetHostName());
            return adresses?.Where(w => w.AddressFamily == AddressFamily.InterNetwork).Select(s => s.ToString()).ToArray();
        }

        public async Task<string[]> GetLocalServer()
        {
            var ips = await GetIPAddress();
            var ist = 0;
            var urls = new string[ips.Length * 254];
            for (var j = 0; j < ips.Length; j++)
            {
                var j1 = j;
                var ip = ips[j];
                var ipmask = ip.Substring(0, ip.LastIndexOf('.'));

                for (var i = 0; i < 255; i++)
                {
                    var i1 = i;
                    var url = $"http://{ipmask}.{i}:5000";
                    new Thread(async () =>
                    {
                        urls[i1 + j1 * 254] = await UrlCanGet(url);
                        ist++;
                    }).Start();
                }
            }
            while (true)
            {
                 Thread.Sleep(100);
                if (ist >= ips.Length * 254)
                {
                    break;
                }
            }
            return urls.Where(w => !string.IsNullOrWhiteSpace(w)).ToArray();
            //throw new NotImplementedException();
        }

        private async Task<string> UrlCanGet(string url, HttpClient hc = null)
        {
            bool hcnull = hc == null;
            if (hcnull) hc = new HttpClient();

            try
            {
                var r = await hc?.GetAsync(url);
                if (r?.IsSuccessStatusCode == true)
                {

                }
                return url;
                //SearchedUrls.Add(s);
            }
            catch (Exception ex)
            {
                // ignored
            }
            finally
            {
                if (hcnull)
                {
                    hc?.Dispose();
                }
            }
            return "";

        }
    }
}